package com.gosling.cloudspace.tools;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.gosling.cloudspace.common.entity.pojo.UserInfoPO;

import java.util.Date;

/**
 * JWT工具类
 *
 * @author lihonglin
 * @date 2022/4/15 16:06
 */
public class JwtTokenTool {
    //定义token返回头部
    public static final String AUTH_HEADER_KEY = "token";
    //token前缀
    public static final String TOKEN_PREFIX = "Bearer ";
    //签名密钥
    public static final String KEY = "q3t6w9z$C&F)J@NcQfTjWnZr4u7x";
    //有效期默认为 24hour * 30 为一个月
    public static final Long EXPIRATION_TIME = 1000L * 60 * 60 * 24 * 30;

    /**
     * 创建TOKEN
     *
     * @param content
     * @return
     */
    public static String createToken(String content) {
        return TOKEN_PREFIX + JWT.create()
                .withSubject(content)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(Algorithm.HMAC512(KEY));
    }

    /**
     * 验证token
     *
     * @param token
     */
    public static UserInfoPO verifyToken(String token) throws Exception {
        try {
            String subject = JWT.require(Algorithm.HMAC512(KEY))
                    .build()
                    .verify(token.replace(TOKEN_PREFIX, ""))
                    .getSubject();
            return JSONObject.parseObject(subject, UserInfoPO.class);
        } catch (TokenExpiredException e) {
            throw new Exception("token已失效，请重新登录", e);
        } catch (JWTVerificationException e) {
            throw new Exception("token验证失败！", e);
        } catch (NullPointerException nullPointerException){
            throw new Exception("空指针异常！", nullPointerException);
        }
    }
}